package com.xiao.tripmateai.controller;

import com.xiao.tripmateai.agent.XManus;
import com.xiao.tripmateai.app.AiService;
import com.xiao.tripmateai.common.BaseResponse;
import com.xiao.tripmateai.common.ResultUtils;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Resource
    private AiService aiService;

    @Resource
    ChatModel dashscopeChatModel;

    @Resource
    private ToolCallbackProvider combinedToolCallbackProvider;

    /**
     * 普通调用 Manus 智能体 (使用统一响应封装)
     */
    @GetMapping("/manus/chat/run")
    public BaseResponse<String> doChatWithManus(String message) {
        XManus xManus = new XManus(dashscopeChatModel, combinedToolCallbackProvider);
        String result = xManus.run(message);
        return ResultUtils.success(result);
    }

    /**
     * 流式调用 Manus 智能体 (保持SSE流式响应)
     */
    @GetMapping("/manus/chat/sse")
    public SseEmitter doChatWithManusSSE(String message) {
        XManus xManus = new XManus(dashscopeChatModel, combinedToolCallbackProvider);
        return xManus.runStream(message);
    }


    /**
     * 流式调用 AI 旅游推荐应用 (保持Flux流式响应)
     */
    @GetMapping(value = "/trip_app/chat/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatWithTripAppSSE(String message, String chatId) {
        return aiService.doChatByStream(message, chatId);
    }

    // Java 示例（使用 Spring WebFlux）
    @GetMapping(value = "/trip_app/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> doChatWithTripApp(String message, String chatId) {
        return aiService.doChatByStream(message, chatId)
                .map(text -> ServerSentEvent.builder(text).build())
                .concatWithValues(ServerSentEvent.builder("[DONE]").event("end").build());
    }
}